package online.heycm.platform.oss.strategy;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import online.heycm.platform.oss.OssProperties;
import online.heycm.platform.oss.OssType;

public class S3Factory {

    /**
     * 创建标准AmazonS3
     *
     * @param properties S3配置
     * @return AmazonS3
     */
    public static AmazonS3 createAmazonS3(OssProperties properties) {
        ClientConfiguration config = new ClientConfiguration();
        config.setMaxConnections(properties.getMaxConnections());
        config.setConnectionTimeout(properties.getConnectionTimeout());
        config.setSocketTimeout(properties.getSocketTimeout());
        config.setProtocol(properties.getProtocol());
        AmazonS3ClientBuilder builder = AmazonS3Client.builder()
                .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(properties.getAccessKey(), properties.getSecretKey())))
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(properties.getEndpoint(), properties.getRegion()))
                .withPathStyleAccessEnabled(properties.isPathStyleAccess())
                .withClientConfiguration(config);
        return builder.build();
    }

    /**
     * 创建策略模式AmazonS3
     *
     * @param properties S3配置
     * @return AmazonS3
     */
    public static AmazonS3 createStrategy(OssProperties properties) {
        S3Strategy strategy = getOssStrategy(properties.getType());
        return strategy == null ? createAmazonS3(properties) : strategy.createAmazonS3(properties);
    }

    private static S3Strategy getOssStrategy(OssType type) {
        switch (type) {
            case MINIO:
                return new MinioStrategy();
            case TENCENT:
                return new TencentStrategy();
            case ALIYUN:
                return new AliyunStrategy();
            case AWS:
                return new AwsStrategy();
            case QINIU:
                return new QiniuStrategy();
            default:
                return null;
        }
    }

}
